import { useEffect, useState } from 'react'
import style from './index.module.less'
import OperateBar from './components/OpeareteBar'
import { CaseContext } from './context'
import { CaseSchema, PartySchema, OtherPersonSchema } from '@src/components/schema/caseSchema'
import { message } from 'antd'
import { awaitWrap } from '@src/assets/js/tool'
import { getCaseDetailRequest, getOthersRequest, getArbitratorsRequest } from './ajax'
import { ArbitratorSchema } from '@src/components/schema/arbitrator'

// 格式化当事人标签
function formatPartyTag (list: PartySchema[]) {
  return list.map(li => {
    if (li.tag) {
      try {
        const tag = JSON.parse(li.tag)
        li = { ...li, ...tag }
      } catch (e) {
        console.error(e)
      }
    }
    return li
  })
}

async function initCaseDetail (id: string, setCaseDetail: (v: CaseSchema) => void) {
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getCaseDetailRequest(id))
  hide()
  if (e === null && d !== null) {
    d.applicants = formatPartyTag(d.applicants || [])
    d.respondents = formatPartyTag(d.respondents || [])
    setCaseDetail(d)
  }
}

async function initOtherPerson (caseid: string,  setOtherPerson: (v: OtherPersonSchema[]) => void) {
  const [e, d] = await awaitWrap(getOthersRequest(caseid))
  if (e === null && d !== null) {
    setOtherPerson(d)
  }
}

async function initArbitrators (caseid: string, setArbitartors: (v: ArbitratorSchema[]) => void) {
  const [e, d] = await awaitWrap(getArbitratorsRequest(caseid))
  if (e === null && d !== null) {
    setArbitartors(d)
  }
}

interface Props {
  meta: {
    id: string,
    operate: string,
    editable: boolean
  }
}

function Main ({ meta }: Props) {
  const [caseDetail, setCaseDetail] = useState<CaseSchema | null>(null)
  const [otherPerson, setOtherPerson] = useState<OtherPersonSchema[]>([])
  const [arbitrators, setArbitrators] = useState<ArbitratorSchema[]>([])
  useEffect(() => {
    if (meta.id) {
      initCaseDetail(meta.id, setCaseDetail)
      initOtherPerson(meta.id, setOtherPerson)
      initArbitrators(meta.id, setArbitrators)
    }
  }, [meta])
  return (
    <CaseContext.Provider value={{
      caseDetail,
      caseid: meta.id,
      operate: meta.operate,
      otherPerson,
      arbitrators,
      editable: meta.editable,
      initCaseDetail: () => { initCaseDetail(meta.id, setCaseDetail) },
      initOtherPerson: () => initOtherPerson(meta.id, setOtherPerson)
    }}>
      <div className={style.container}>
        <OperateBar />
      </div>
    </CaseContext.Provider>
  )
}

export default Main
